# -*- coding: utf-8 -*-
# backend/services/websocket_service.py
from typing import Dict, List, Any, Optional
from datetime import datetime
import asyncio
import json

from backend.models.websocket_event import WebSocketEvent, WebSocketConnection
from backend.core.database import AsyncSession
from backend.utils.logger import logger


class WebSocketEventService:
    """WebSocket事件服务"""
    
    def __init__(self):
        self.event_handlers: Dict[str, List[Callable]] = {}
    
    def register_handler(self, event_type: str, handler: Callable):
        """注册事件处理器"""
        if event_type not in self.event_handlers:
            self.event_handlers[event_type] = []
        self.event_handlers[event_type].append(handler)
    
    async def trigger_event(
        self, 
        event_type: str, 
        event_data: Dict[str, Any],
        user_id: str,
        project_id: Optional[str] = None,
        connection_id: Optional[str] = None
    ):
        """触发事件"""
        
        handlers = self.event_handlers.get(event_type, [])
        
        for handler in handlers:
            try:
                await handler(event_type, event_data, user_id, project_id, connection_id)
            except Exception as e:
                logger.error(f"事件处理器执行失败 - 类型: {event_type}, 错误: {str(e)}")
    
    async def save_event(
        self,
        db: AsyncSession,
        user_id: str,
        event_type: str,
        event_data: Dict[str, Any],
        project_id: Optional[str] = None,
        connection_id: Optional[str] = None
    ):
        """保存事件到数据库"""
        
        try:
            event = WebSocketEvent(
                user_id=user_id,
                project_id=project_id,
                connection_id=connection_id or "",
                event_type=event_type,
                event_data=event_data,
                timestamp=datetime.utcnow()
            )
            
            db.add(event)
            await db.commit()
            
        except Exception as e:
            logger.error(f"保存WebSocket事件失败: {str(e)}")
            await db.rollback()


# 事件处理器示例

async def handle_code_change_event(
    event_type: str,
    event_data: Dict[str, Any],
    user_id: str,
    project_id: Optional[str],
    connection_id: Optional[str]
):
    """处理代码变更事件"""
    
    logger.info(f"代码变更事件 - 用户: {user_id}, 项目: {project_id}, 文件: {event_data.get('file_id')}")
    
    # 这里可以添加自动保存、备份等逻辑
    # 例如：定期保存代码快照、检测语法错误等


async def handle_user_activity_event(
    event_type: str,
    event_data: Dict[str, Any],
    user_id: str,
    project_id: Optional[str],
    connection_id: Optional[str]
):
    """处理用户活动事件"""
    
    logger.info(f"用户活动事件 - 用户: {user_id}, 活动: {event_type}")
    
    # 更新用户最后活动时间
    # 统计用户使用情况等


# 初始化事件服务
websocket_event_service = WebSocketEventService()

# 注册事件处理器
websocket_event_service.register_handler("code_change", handle_code_change_event)
websocket_event_service.register_handler("user_activity", handle_user_activity_event)

